<template>
  <!-- action="#" :auto-upload="false" 因为我们要自己去手动上传到腾讯云，所以我们把自动上传关闭 -->
  <div>
    <!-- change -->
    <el-upload
      list-type="picture-card"
      action="#"
      :auto-upload="false"
      :on-preview="preview"
      :limit="limit"
      :file-list="fileList"
      :class="{hide:limit===fileList.length}"
      :on-change="handleChange"
      :on-remove="handleRemove"
    >
      <i class="el-icon-plus" />

    </el-upload>
    <el-dialog :visible.sync="visible" :show-close="false">
      <img :src="src" style="width:80%;margin:0 auto;display:block;" alt="">
    </el-dialog>
  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5' // 通过npm安装的sdk
const cos = new COS({
  SecretId: 'AKIDmKF1OZnGwPeh9MR6bwUofX80vd6OBRM9',
  SecretKey: 'jCevznLEwOaVIYaNYaXGjxxlKfw8G9nX'
})
export default {
  props: {
    // 默认情况下只能上传一张图片
    limit: {
      type: Number,
      default: 1
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      src: '',
      visible: false,
      fileList: []
    }
  },
  created() {
    this.fileList = this.list
  },

  methods: {
    preview(file) {
      this.visible = true
      this.src = file.url
    },
    handleChange(file1, fileList) {
      // this.fileList = []
      this.fileList = fileList
      // console.log(file)
      const file = file1.raw
      /* 直接调用cos sdk的方法 */
      cos.uploadFile({
        Bucket: '12334heima-1300357219', /* 填写自己的bucket，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + '.jpg', /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功')
          console.log(data)
          // this.fileList.push({ url: 'https://' + data.Location, status: 'success' })
          this.fileList[0].status = 'success'
          this.fileList[0].url = 'https://' + data.Location
        }
      })
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header{
  display: none;
}

::v-deep .el-dialog__body{
  padding:0;
}

::v-deep .hide .el-upload--picture-card{
  display: none;
}

// ::v-deep .el-list-enter-active{
//   transition: none !important;
// }

// ::v-deep .el-list-leave-active{
//   transition: none !important;
// }

</style>
